package org.mixed.config;

import lombok.extern.slf4j.Slf4j;
import org.mixed.core.domain.MixNotify;
import org.mixed.core.utils.JsonUtils;
import org.mixed.service.MixApiService;
import org.mixed.service.websocket.MixNotifyService;
import org.mixed.service.websocket.MixSynchronizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import java.util.Arrays;

@Slf4j
@Configuration
public class MixClusterConfiguration {
    @Autowired
    private MixProperties properties;

    @Bean
    public MixNotifyService magicNotifyService(RedisModule redisModule) {
        return magicNotify -> redisModule.execute("publish",
                Arrays.asList(properties.getChannel(), JsonUtils.toJsonString(magicNotify)));
    }

    /**
     * 消息处理服务
     */
    @Bean
    public MixSynchronizationService magicSynchronizationService(MixNotifyService magicNotifyService) {
        return new MixSynchronizationService(magicNotifyService, properties.getInstanceId());
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory redisConnectionFactory, MixApiService mixApiService) {
        log.info("开启集群通知监听， Redis channel: {}", properties.getChannel());
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        redisMessageListenerContainer.addMessageListener((message, pattern) ->
                mixApiService.processNotify(JsonUtils.readValue(message.getBody(), MixNotify.class)),
                ChannelTopic.of(properties.getChannel()));
        return redisMessageListenerContainer;
    }
}
